package controllers

import (
	"dmsv/common"
	"dmsv/models"
	"dmsv/process"
	"encoding/json"
	"github.com/beego/beego/v2/core/logs"
	"strconv"
	"time"
)

type IvrController struct {
	BaseController
}

func (this *IvrController) URLMapping() {
	this.Mapping("add", this.IvrAdd)
	this.Mapping("update", this.IvrUpdate)
	this.Mapping("del", this.IvrDel)
	this.Mapping("publish", this.IvrPublish)
	this.Mapping("basicVoiceOffwork", this.IvrBasicOffWork)
	this.Mapping("basicVoiceWait", this.IvrBasicWait)
	this.Mapping("basicVoiceOthers", this.IvrBasicOthers)
	this.Mapping("satisfactionSurvey", this.SatisfactionSurvey)
}

// @Title 添加ivr
// @Description 管理界面添加ivr名称
// @Param   param   body       controllers.IvrParam     true   ""
// @Success 200     {object}   controllers.Code
// @router  /add [post]
func (this *IvrController) IvrAdd() {

	logs.Debug("receive:%v", string(this.Ctx.Input.RequestBody))
	param := IvrParam{}
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &param); err != nil {
		this.Data["json"] = ParamsError
		this.ServeJSON()
		return
	}

	activeTime := make([]process.IvrTimeActive, 0)
	for _, t := range param.ActiveTime {

		at := process.IvrTimeActive{}
		from, err := time.ParseInLocation("15:04", t.From, time.Local)
		if err != nil {
			logs.Error("起始时间错误:%v ,err:%v", t.From, err)
		}
		end, err := time.ParseInLocation("15:04", t.End, time.Local)
		if err != nil {
			logs.Error("起始时间错误:%v ,err:%v", t.End, err)
		}

		at.ActiveFrom = from
		at.ActiveEnd = end
		logs.Debug("ivr[%v] 起始时间:%v 结束时间:%v", param.IvrId,
			from.Format("2006-01-02 15:04:05"), end.Format("2006-01-02 15:04:05"))
		activeTime = append(activeTime, at)
	}

	weeks := common.WeekParse(param.Day)

	err := process.IvrManageAdd(param.IvrId, param.AppId, param.Name, param.Number, activeTime, weeks)
	this.Data["json"] = errorTransfer(err)
	this.ServeJSON()

	return
}

// @Title 修改ivr
// @Description 管理界面修改ivr相关信息
// @Param   param   body       controllers.IvrParam     true   ""
// @Success 200     {object}   controllers.Code
// @router  /update [post]
func (this *IvrController) IvrUpdate() {

	logs.Debug("receive:%v", string(this.Ctx.Input.RequestBody))
	param := IvrParam{}
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &param); err != nil {
		this.Data["json"] = ParamsError
		this.ServeJSON()
		return
	}

	activeTime := make([]process.IvrTimeActive, 0)
	for _, t := range param.ActiveTime {

		at := process.IvrTimeActive{}
		from, err := time.ParseInLocation("15:04", t.From, time.Local)
		if err != nil {
			logs.Error("开始时间错误:%v ,err:%v", t.From, err)
			this.Data["json"] = MakeSysErrCode(err.Error())
			this.ServeJSON()
			return
		}
		end, err := time.ParseInLocation("15:04", t.End, time.Local)
		if err != nil {
			logs.Error("结束时间错误:%v ,err:%v", t.End, err)
			if t.End == "24:00" {
				end, _ = time.ParseInLocation("15:04", "23:59", time.Local)
			} else {
				this.Data["json"] = MakeSysErrCode(err.Error())
				this.ServeJSON()
				return
			}
		}

		if from.After(end) {
			this.Data["json"] = MakeSysErrCode("开始时间应该小于结束时间")
			this.ServeJSON()
			return
		}

		at.ActiveFrom = from
		at.ActiveEnd = end
		logs.Debug("ivr[%v] 起始时间:%v 结束时间:%v", param.IvrId,
			from.Format("2006-01-02 15:04:05"), end.Format("2006-01-02 15:04:05"))
		activeTime = append(activeTime, at)
	}
	weeks := common.WeekParse(param.Day)
	err := process.IvrManageUpdate(param.IvrId, param.AppId, param.Name, param.Number, activeTime, weeks)
	this.Data["json"] = errorTransfer(err)
	this.ServeJSON()

	return
}

// @Title 删除ivr
// @Description 删除ivr
// @Param   param   body       controllers.IvrParam     true   ""
// @Success 200     {object}   controllers.Code
// @router  /del [post]
func (this *IvrController) IvrDel() {

	logs.Debug("receive:%v", string(this.Ctx.Input.RequestBody))
	param := IvrParam{}
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &param); err != nil {
		this.Data["json"] = ParamsError
		this.ServeJSON()
		return
	}

	err := process.IvrManageDel(param.IvrId, param.AppId)
	this.Data["json"] = errorTransfer(err)
	this.ServeJSON()

	return
}

// @Title ivr发布
// @Description ivr发布生效
// @Param   param   body       controllers.IvrParam     true   ""
// @Success 200     {object}   controllers.Code
// @router  /publish [post]
func (this *IvrController) IvrPublish() {

	logs.Debug("发布ivr receive:%v", string(this.Ctx.Input.RequestBody))
	param := IvrParam{}
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &param); err != nil {
		this.Data["json"] = ParamsError
		this.ServeJSON()
		return
	}

	err := process.IvrManagePublish(param.IvrId, param.AppId)
	this.Data["json"] = errorTransfer(err)
	this.ServeJSON()

	return
}

// @Title ivr基础配置下班语音
// @Description ivr基础配置
// @Success 200     {object}   controllers.Code
// @router  /basicVoiceOffwork [post]
func (this *IvrController) IvrBasicOffWork() {

	logs.Debug("receive IvrBasicOffWork request:%v", string(this.Ctx.Input.RequestBody))

	request := make(map[string]string)

	err := json.Unmarshal(this.Ctx.Input.RequestBody, &request)
	if err != nil {
		logs.Error("ivr基础设置 下班语音json解析失败:%v;err:%v", string(this.Ctx.Input.RequestBody), err)
		this.Data["json"] = ParamsError
		this.ServeJSON()
		return
	}

	appId := request["appId"]
	afterWork := request["afterVoice"]
	messageVoice := request["messageVoice"]
	leaveMsg := request["leaveMsg"]

	logs.Debug("appId:%v ;下班语音:%v ，留言设置:%v,留言开关:%v", appId, afterWork, messageVoice, leaveMsg)
	err = process.SetCompanyOffWorkVoice(appId, afterWork, messageVoice, leaveMsg)
	if err != nil {
		this.Data["json"] = QueRegFail
		this.ServeJSON()
		return
	}

	this.Data["json"] = Success
	this.ServeJSON()

	return
}

// @Title ivr基础配置-等待语音
// @Description ivr基础配置
// @Success 200     {object}   controllers.Code
// @router  /basicVoiceWait [post]
func (this *IvrController) IvrBasicWait() {
	logs.Debug("receive IvrBasicWait request:%v", string(this.Ctx.Input.RequestBody))

	type reqParam struct {
		AppId      string            `json:"appId"`
		TipVoice   string            `json:"tipVoice"`   //提示语音
		PlayWait   map[string]string `json:"playBlank"`  //等待次数
		NextAction map[string]string `json:"nextAction"` //执行动作
	}

	request := &reqParam{}
	err := json.Unmarshal(this.Ctx.Input.RequestBody, request)
	if err != nil {
		logs.Error("ivr基础设置 等待语音json解析失败:%v;err:%v", string(this.Ctx.Input.RequestBody), err)
		this.Data["json"] = ParamsError
		this.ServeJSON()
		return
	}
	count := request.PlayWait["againWaitTime"]
	playTime, _ := strconv.Atoi(count)

	count = request.PlayWait["userWaitTime"]
	stopSec, _ := strconv.Atoi(count)

	endVoice := request.NextAction["endVoice"]
	leaveVoice := request.NextAction["messageVoice"]

	nextVoice := ""
	leaveMsg := ""
	if endVoice == "disable" {
		//直接挂机
		nextVoice = "disable"
		leaveMsg = "false"
	} else {
		if len(endVoice) > 0 {
			//放音完成后挂机
			nextVoice = endVoice
			leaveMsg = "false"
		} else if len(leaveVoice) > 0 {

			//放音完成后留言
			nextVoice = leaveVoice
			leaveMsg = "true"
		}
	}

	err = process.SetCompanyWaitVoice(request.AppId, request.TipVoice, nextVoice, leaveMsg, playTime, stopSec)
	if err != nil {
		this.Data["json"] = AppIdNotExist
		this.ServeJSON()
		return
	}

	this.Data["json"] = Success
	this.ServeJSON()

	return
}

// @Title ivr基础配置-其他语音
// @Description ivr基础配置
// @Success 200     {object}   controllers.Code
// @router  /basicVoiceOthers [post]
func (this *IvrController) IvrBasicOthers() {

	logs.Debug("receive IvrBasicOthers request:%v", string(this.Ctx.Input.RequestBody))

	request := make(map[string]string)

	err := json.Unmarshal(this.Ctx.Input.RequestBody, &request)
	if err != nil {
		logs.Error("ivr基础设置 其他语音json解析失败:%v;err:%v", string(this.Ctx.Input.RequestBody), err)
		this.Data["json"] = ParamsError
		this.ServeJSON()
		return
	}

	appId := request["appId"]
	//按键语音
	keyErrVoice := request["dtmfErrorVoice"]
	//保持语音
	keepVoice := request["keepVoice"]
	//播放坐席工号
	playServiceId := request["playSeatId"]
	//播放转坐席提示
	playSerciceCall := request["playSeatCallTip"]
	//提示坐席开始说话
	notifyServiceTalk := request["promptSeatTalk"]

	process.SetPlayServiceId(appId, playServiceId)
	logs.Debug("%v 设置其他基础语音:%v %v %v %v %v", appId, keyErrVoice, keepVoice, playServiceId, playSerciceCall, notifyServiceTalk)
	this.Data["json"] = Success
	this.ServeJSON()

	return
}

type SatisfactionParam struct {
	AppId    string `json:"appId"`
	Active   string `json:"active"`
	AutoSend string `json:"autoSend"`
	TipVoice string `json:"tipVoice"`
	EndVoice string `json:"endVoice"`
}

// @Title 满意度配置
// @Description 满意度配置
// @Param   param   body       controllers.SatisfactionParam     true   ""
// @Success 200     {object}   controllers.Code
// @router  /satisfactionSurvey [post]
func (this *IvrController) SatisfactionSurvey() {

	logs.Debug("receive SatisfactionSurvey request:%v", string(this.Ctx.Input.RequestBody))
	request := make(map[string]string)

	err := json.Unmarshal(this.Ctx.Input.RequestBody, &request)
	if err != nil {
		logs.Error("满意度设置 son解析失败:%v;err:%v", string(this.Ctx.Input.RequestBody), err)
		this.Data["json"] = ParamsError
		this.ServeJSON()
		return
	}

	appId := request["appId"]
	active := request["active"]
	autoSend := request["autoSend"]
	tipVoice := request["tipVoice"]
	endVoice := request["endVoice"]

	err = process.SatisfactionConfig(appId, active, autoSend, tipVoice, endVoice)
	if err != nil {
		this.Data["json"] = QueRegFail
	} else {
		this.Data["json"] = Success
	}

	//配置入库
	models.UpdateCompanySatisfaction(appId, active, autoSend, tipVoice, endVoice)
	this.ServeJSON()
}

func errorTransfer(err error) *Code {

	if err == nil {
		return Success
	}

	switch err.Error() {
	case "NoCompany":
		return QueRegFail
	case "ivrIdErr":
		return IvrIdErr
	default:
		return Success
	}

}
